package com.ellecity06.cwhiskymall.base

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout
import androidx.viewbinding.ViewBinding
import com.chad.library.adapter.base.QuickAdapterHelper
import com.chad.library.adapter.base.loadState.LoadState
import com.chad.library.adapter.base.loadState.trailing.TrailingLoadStateAdapter
import com.ellecity06.common.adapter.CustomLoadMoreAdapter
import com.ellecity06.common.base.BaseAdapter
import com.ellecity06.common.base.BaseMvvmFragment
import com.ellecity06.common.base.BaseViewModel
import com.ellecity06.common.databinding.LayoutEmptyViewBinding
import com.ellecity06.common.ktx.clearAnimations
import com.ellecity06.common.ktx.finishRefresh
import com.ellecity06.common.ktx.observeEvent
import com.ellecity06.common.ktx.onDebounceClick
import com.ellecity06.common.utils.ToastUtils
import com.ellecity06.cwhiskymall.base.vm.PageIntent
import com.ellecity06.cwhiskymall.base.vm.PageState

/**
 * @author ellecity06
 * @time 2025/1/2 17:50
 * @des 列表 fragment
 */
abstract class BasePageFragment< VB : ViewBinding, out VM : BaseViewModel>:BaseMvvmFragment<VB,VM>() ,   TrailingLoadStateAdapter.OnTrailingListener, SwipeRefreshLayout.OnRefreshListener {
    open val refreshLayout: SwipeRefreshLayout? = null
    open val recyclerView: RecyclerView? = null
    open val adapter: BaseAdapter<out Any, out ViewBinding>? = null
    private var adapterHelper: QuickAdapterHelper? = null
    open val layoutManager: RecyclerView.LayoutManager by lazy { LinearLayoutManager(requireActivity()) }

    /**
     * 是否开启加载更多
     */
    open val enableLoadMore: Boolean = true

    /**
     * 是否开启加载更多
     */
    open val enableEmpty: Boolean = true

    private val emptyViewBinding by lazy { LayoutEmptyViewBinding.inflate(LayoutInflater.from(requireActivity()), recyclerView, false) }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        handlerView()
        collectPageState()
    }
    private fun handlerView() {
        refreshLayout?.setOnRefreshListener(this)
        recyclerView?.layoutManager = layoutManager
        recyclerView?.clearAnimations()
        recyclerView?.let {
            if (enableEmpty) {
                adapter?.emptyView = emptyViewBinding.root
            }
            adapter?.isEmptyViewEnable = true
            emptyViewBinding.ivEmpty.onDebounceClick(::onEmptyClick)
            emptyViewBinding.tvTips.onDebounceClick(::onEmptyClick)

            if (enableLoadMore) {
                val loadMoreAdapter = CustomLoadMoreAdapter()
                loadMoreAdapter.setOnLoadMoreListener(this)
                adapterHelper = QuickAdapterHelper.Builder(adapter!!)
                    .setTrailingLoadStateAdapter(loadMoreAdapter)
                    .build()
//                adapterHelper?.trailingLoadStateAdapter?.isAutoLoadMore = false
                recyclerView?.adapter = adapterHelper?.adapter
            } else {
                recyclerView?.adapter = adapter
            }

        }

    }

    open fun onEmptyClick(view: View) {
        onRefresh()
    }



    override fun onRefresh() {
        if (viewModel is BasePageViewModel<*, *>) {
            lifecycleScope.launchWhenCreated {
                (viewModel as BasePageViewModel<*, *>).pageIntent.send(PageIntent.Refresh)
            }

        }
    }

    private fun loadMore() {
        if (viewModel is BasePageViewModel<*, *>) {
            lifecycleScope.launchWhenCreated {
                (viewModel as BasePageViewModel<*, *>).pageIntent.send(PageIntent.LoadMore)
            }
        }
    }

    private fun collectPageState() {
        if (viewModel is BasePageViewModel<*, *>) {
            (viewModel as BasePageViewModel<*, *>).pageState.observeEvent(this) {
                when (it) {
                    PageState.LoadError -> {
                        refreshLayout?.finishRefresh()
                    }
                    is PageState.LoadMoreSuccess -> {
                        adapter?.addAll(it.list as List<Nothing>)
                        adapterHelper?.trailingLoadState = LoadState.NotLoading(!it.hasMore)
                    }

                    PageState.NoMore -> {
                        refreshLayout?.finishRefresh()
                        adapterHelper?.trailingLoadState = LoadState.None
                    }

                    is PageState.RefreshSuccess -> {
                        adapter?.submitList(it.list as List<Nothing>)
                        refreshLayout?.finishRefresh()
                        if (it.hasMore) {
                            adapterHelper?.trailingLoadState = LoadState.NotLoading(false)
                        } else {
                            adapterHelper?.trailingLoadState = LoadState.None
                        }
                    }
                    is PageState.RefreshError -> {
                        refreshLayout?.finishRefresh()
                        ToastUtils.show(it.msg)
                    }
                }
            }
        }
    }
    override fun onFailRetry() {
        loadMore()
    }

    override fun onLoad() {
        loadMore()
    }
}